"use client"

import { useState } from 'react';
import { updatePlayerTier } from '@/lib/data';
import { PlayerResponse } from '@/lib/types';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogTrigger,
  DialogFooter,
  DialogClose
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Pencil } from 'lucide-react';

interface EditPlayerTiersProps {
  player: PlayerResponse;
}

export default function EditPlayerTiers({ player }: EditPlayerTiersProps) {
  const [swordTier, setSwordTier] = useState<string | null>(player.swordTier?.toString() || null);
  const [crystalTier, setCrystalTier] = useState<string | null>(player.crystalTier?.toString() || null);
  const [buhcTier, setBuhcTier] = useState<string | null>(player.buhcTier?.toString() || null);
  const [potionTier, setPotionTier] = useState<string | null>(player.potionTier?.toString() || null);
  const [npotTier, setNpotTier] = useState<string | null>(player.npotTier?.toString() || null);
  const [smpTier, setSmpTier] = useState<string | null>(player.smpTier?.toString() || null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  
  const handleSubmit = async () => {
    try {
      setIsSubmitting(true);
      setError(null);
      setSuccess(false);
      
      // 从状态中收集值并转换为适当的类型
      const tierData: any = {};
      
      if (swordTier !== null) tierData.swordTier = parseInt(swordTier);
      if (crystalTier !== null) tierData.crystalTier = parseInt(crystalTier);
      if (buhcTier !== null) tierData.buhcTier = parseInt(buhcTier);
      if (potionTier !== null) tierData.potionTier = parseInt(potionTier);
      if (npotTier !== null) tierData.npotTier = parseInt(npotTier);
      if (smpTier !== null) tierData.smpTier = parseInt(smpTier);
      
      // 调用API更新玩家段位
      await updatePlayerTier(player.id, tierData);
      
      setSuccess(true);
      
      // 2秒后刷新页面以获取更新
      setTimeout(() => {
        window.location.reload();
      }, 2000);
    } catch (err) {
      setError('更新段位失败，请稍后重试');
      console.error('Error updating tiers:', err);
    } finally {
      setIsSubmitting(false);
    }
  };
  
  const tierOptions = [1, 2, 3, 4, 5];
  
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="flex items-center gap-2">
          <Pencil className="h-3 w-3" />
          <span>编辑段位</span>
        </Button>
      </DialogTrigger>
      <DialogContent className="bg-[#2a2e35] border-gray-700 text-white sm:max-w-md">
        <DialogHeader>
          <DialogTitle>编辑 {player.name} 的段位</DialogTitle>
        </DialogHeader>
        
        <div className="grid grid-cols-2 gap-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="swordTier">剑术模式</Label>
            <Select 
              value={swordTier || ''} 
              onValueChange={(value) => setSwordTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="crystalTier">水晶模式</Label>
            <Select 
              value={crystalTier || ''} 
              onValueChange={(value) => setCrystalTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="buhcTier">终极战斗</Label>
            <Select 
              value={buhcTier || ''} 
              onValueChange={(value) => setBuhcTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="potionTier">药剂大师</Label>
            <Select 
              value={potionTier || ''} 
              onValueChange={(value) => setPotionTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="npotTier">新药剂试炼</Label>
            <Select 
              value={npotTier || ''} 
              onValueChange={(value) => setNpotTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="smpTier">生存模式</Label>
            <Select 
              value={smpTier || ''} 
              onValueChange={(value) => setSmpTier(value === '' ? null : value)}
            >
              <SelectTrigger className="bg-[#1a1d24]">
                <SelectValue placeholder="选择等级" />
              </SelectTrigger>
              <SelectContent className="bg-[#1a1d24]">
                <SelectItem value="">无</SelectItem>
                {tierOptions.map(tier => (
                  <SelectItem key={tier} value={tier.toString()}>
                    Tier {tier}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
        
        {error && (
          <div className="text-red-500 text-sm">{error}</div>
        )}
        
        {success && (
          <div className="text-green-500 text-sm">段位更新成功！页面即将刷新...</div>
        )}
        
        <DialogFooter className="flex flex-row justify-end gap-2">
          <DialogClose asChild>
            <Button variant="outline" className="bg-transparent">取消</Button>
          </DialogClose>
          <Button 
            onClick={handleSubmit} 
            disabled={isSubmitting}
            className="bg-blue-600 hover:bg-blue-700"
          >
            {isSubmitting ? '保存中...' : '保存更改'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
} 